//
// Created by root on 19-8-1.
//

#include <unistd.h>
#include "hook_camera_v1.h"
#include "log_utils.h"
#include "inject_compacter.h"
#include "AndHook.h"
#include "string_utils.h"
#include "jni_utils.h"

#define TAG "CameraV1"

static jmethodID old_method= nullptr;

#define OPERATION_NAME "cameraInitVersion"

//private int cameraInitVersion(int cameraId, int halVersion)
int my_camera_init_version(JNIEnv *env,jobject instance,
        int cameraId,int halVersion){
    if(!old_method){
        LOGE("old_method is nullptr\n");
        return JNI_ERR;
    }
    std::string operation=std::string(OPERATION_NAME);
    operation.append(":");
    operation.append(itoa(cameraId));
    if(!post_auth_request(env,operation)){
        LOGE("user denies to let process:%d use camera:%d\n", getpid(), cameraId);
        return JNI_ERR;
    }
    LOGD("user allows to let process:%d use camera:%d\n", getpid(), cameraId);

    int init_ret=env->CallIntMethod(instance,old_method,
            cameraId,halVersion);
    return init_ret;
}

void hook_camera_v1(JNIEnv *env) {
    if(old_method)
        return;
    jclass camera_class=env->FindClass("android/hardware/Camera");
    ////private int cameraInitVersion(int cameraId, int halVersion)
    jmethodID camera_init_version=env->GetMethodID(camera_class,
            "cameraInitVersion","(II)I");
    if(!camera_init_version&&TryCatch(env))
        return;
    AKJavaHookMethodV(env,camera_init_version,
            reinterpret_cast<void*>(my_camera_init_version),&old_method);
    LOGD("old_method:%p\n",old_method);
}
